package com.googlecode.jwsm.security.basic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.jwsm.Log;
import com.googlecode.jwsm.Uploader;
import com.googlecode.jwsm.security.SecurityFactory;
import com.googlecode.jwsm.security.SuperUser;
import com.googlecode.jwsm.security.User;

public class BasicSecurityFactory implements SecurityFactory {
	private Map<String, String> authentication;
	
	public BasicSecurityFactory() {
		authentication = new HashMap<String, String>();
		File directory = new File(Uploader.getDirectoryString());
		File usersList = new File(directory, "users.list");
		if (usersList.exists()) {
			try {
				BufferedReader reader = new BufferedReader(new FileReader(usersList));
				String line;
				while ((line = reader.readLine()) != null) {
					int position = line.indexOf('=');
					String username = line.substring(0, position);
					String password = line.substring(position + 1);
					authentication.put(username, password);
					Log.fine("User added to authentication list: " + username);
				}
			} catch(Throwable t) {
				Log.get().log(Level.SEVERE, "Error occurred while processing users.list file (" + usersList.getAbsoluteFile() + "). File should consist of one \"username=password\" entry per line.", t);
			}
		} else {
			Log.warn("Unable to find users list: " + usersList.getAbsolutePath() + " - Loading default user: admin with password admin");
			authentication.put("admin", "admin");
		}
	}
	
	public User login(String username, String password) {
		String value = authentication.get(username);
		if (password.equals(value)) {
			return new SuperUser(username);
		}
		return null;
	}

	public User login(HttpServletRequest request, HttpServletResponse response, String formURL) {
		User user = null;
		try {
			user = login(request, response);
		} catch (SecurityException exc) {
			exc.printStackTrace();
		}
		if (user == null && formURL != null) try {
			response.sendRedirect(formURL);
		} catch (IOException exc) {
			throw new SecurityException("Problem occurred trying to redirect to form based login: " + formURL);
		}
		return user;
	}

	public User login(HttpServletRequest request, HttpServletResponse response) {
		if (request.getSession().getAttribute("jwsm.user") != null) {
			return (User) request.getSession().getAttribute("jwsm.user");
		}
		User user = null;
		if (request.getHeader("username") != null) {
			String username = request.getHeader("username");
			String password = request.getHeader("password");
			user = login(username, password);
		} else if (request.getParameter("username") != null) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			user = login(username, password);
		}
		request.getSession().setAttribute("jwsm.user", user);
		return user;
	}

	public void logout(HttpServletRequest request, HttpServletResponse response, String s) {
		request.getSession().removeAttribute("jwsm.user");
		try {
			response.sendRedirect(request.getRequestURL().toString());
		} catch (IOException exc) {
			throw new SecurityException(exc.getMessage());
		} catch (IllegalStateException exc) {
		}
	}

	public Object getApplicationProperty(String s) {
		return null;
	}
	
	public void setApplicationProperty(String s, Serializable serializable) {
	}
}